package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.landinfo.config.Constants;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.Authority;
import com.landinfo.domain.User;
import com.landinfo.repository.UserRepository;
import com.landinfo.service.MailService;
import com.landinfo.service.UserService;
import com.landinfo.service.dto.UserDTO;
import com.landinfo.service.dto.UserDTO2;
import com.landinfo.service.mapper.UserMapper;
import com.landinfo.web.rest.vm.ManagedUserVM;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.net.URISyntaxException;
import java.time.Instant;
import java.util.*;

@RestController
@RequestMapping("/api")
public class UserResource {

    private final Logger log = LoggerFactory.getLogger(UserResource.class);

    private static final String ENTITY_NAME = "userManagement";

    private final UserRepository userRepository;

    private final MailService mailService;

    private final UserService userService;

    private final UserMapper userMapper;


    public UserResource(UserRepository userRepository, MailService mailService,
                        UserService userService, UserMapper userMapper) {

        this.userRepository = userRepository;
        this.mailService = mailService;
        this.userService = userService;
        this.userMapper = userMapper;
    }

    @PostMapping("/users")
    @Timed
    // @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity createUser(@RequestBody ManagedUserVM managedUserVM) throws URISyntaxException {
        if (managedUserVM.getId() != null) {
            return ResponseEntity.badRequest()
                .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new user cannot already have an ID"))
                .body("A new user cannot already have an ID");
            // Lowercase the user login before comparing with database
        } else if (userRepository.findOneByLogin(managedUserVM.getLogin()).isPresent()) {
            return ResponseEntity.badRequest()
                .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "userexists", "Login already in use"))
                .body("Login already in use");
        } else {
            String oldPwd=managedUserVM.getPassword();
            managedUserVM.setPassword("a111111a");
            User newUser = null;
            try {
                newUser = userService.createUser(managedUserVM);
                userService.changeUserPassword(newUser.getLogin(), oldPwd);
            } catch (Exception ex) {
                String message = ex.getLocalizedMessage();
                return ResponseEntity.badRequest()
                    .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "error", message))
                    .body(message);
            }
            return ResponseEntity.ok(newUser);
        }
    }

    @PutMapping("/users")
    @Timed
//    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<UserDTO> updateUser(@RequestBody ManagedUserVM managedUserVM) {
        log.debug("REST request to update User : {}", managedUserVM);
        managedUserVM.setLastModifiedDate(Instant.now());
        Optional<User> existingUser = userRepository.findOneByLogin(managedUserVM.getLogin());
        if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "userexists", "Login already in use")).body(null);
        }
        Optional<UserDTO> updatedUser = userService.updateUser(managedUserVM);

        return ResponseUtil.wrapOrNotFound(updatedUser,
            HeaderUtil.createAlert("userManagement.updated", managedUserVM.getLogin()));
    }

    /**
     * GET  /users : get all users.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and with body all users
     */
    @GetMapping("/users")
    @Timed
    public ResponseEntity<String> getAllUsers(@ApiParam Pageable pageable) {
        final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
        List<UserDTO> userDTOS = page.getContent();
        String result = "";
        try {
            result = JSON.toJSONString(userDTOS, SerializerFeature.DisableCircularReferenceDetect);
        } catch (Exception ex) {
            ex.printStackTrace();
            result = ex.getLocalizedMessage();
        }
        return new ResponseEntity<>(result, headers, HttpStatus.OK);
    }

    @PostMapping("/users/getChildUsers")
    @Timed
    public ResponseEntity<String> getChildUsers(@RequestBody UserDTO account) {
        log.debug("REST request to get User : {}", account);
        String result = "";
        try {
            String authorityId = "";
            if(account != null && account.getAuthorities() != null
                && account.getAuthorities().size() > 0){
                Object[] authorities = account.getAuthorities().toArray();
                authorityId = (String)authorities[0];
            }else if (account != null && account.getId() != null){
                User user = this.getUserByLogin(account.getLogin());
                if (user.getAuthorities() != null && user.getAuthorities().size() > 0) {
                    Object[] authorities = user.getAuthorities().toArray();
                    authorityId = ((Authority) authorities[0]).getName();
                }
            }
            List<User> users = null;
            if (authorityId != null && !authorityId.equals("")) {
                users = userService.getAllUsersByAuthorityId(authorityId);
            } else {
                System.out.println("pigpq!");
            }
            List<UserDTO> userDTOS = this.userMapper.usersToUserDTOs(users);
            try {
                result = JSON.toJSONStringWithDateFormat(userDTOS, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);
            } catch (StackOverflowError ex) {
                ex.printStackTrace();
                result = ex.getLocalizedMessage();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = ex.getLocalizedMessage();
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * GET  /users/:login : get the "login" user.
     *
     * @param login the login of the user to find
     * @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
     */
    @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
    @Timed
    public ResponseEntity<UserDTO2> getUser(@PathVariable String login) {
        log.debug("REST request to get User : {}", login);
        return ResponseUtil.wrapOrNotFound(
            userService.getUserWithAuthoritiesByLogin(login)
                .map(UserDTO2::new));
    }

    private User getUserByLogin(String login) {
        return userService.getUserWithAuthoritiesByLogin(login).get();
    }

    /**
     * DELETE /users/:login : delete the "login" User.
     *
     * @param login the login of the user to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/users/{login}")
    @Timed
//    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteUser(@PathVariable String login) {
        log.debug("REST request to delete User: {}", login);
        userService.deleteUser(login);
        return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
    }

    @DeleteMapping("/users/delById/{id}")
    @ApiIgnore
    public ResponseEntity<Void> deleteById(@PathVariable String id) {
        userService.deleteUserById(id);
        return ResponseEntity.ok().headers(HeaderUtil.createAlert("A user is deleted with identifier " + id, id)).build();
    }


    @GetMapping("/users/getAll/{authorityId}")
    @Timed
    public String getAllUsersByAuthorityId(@PathVariable String authorityId) {
        List<User> users = userService.getAllUsersByAuthorityId(authorityId);
//        Authority authority = userService.findOne(id);
        if (users == null) {
            return null;
        } else {
            return JSON.toJSONString(users,SerializerFeature.DisableCircularReferenceDetect);
        }
    }

    @GetMapping("/users/getAllUsers")
    @Timed
    public String getAllUsers() {
        List<User> users = userService.getAllUsers();
        if (users == null) {
            return null;
        } else {
            return JSON.toJSONString(users,SerializerFeature.DisableCircularReferenceDetect);
        }
    }

}


